#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试akshare库中的13个期权数据获取接口
"""

import akshare as ak
from datetime import datetime
import time


def print_separator(title):
    """打印分隔符"""
    print("\n" + "=" * 80)
    print(f"  {title}")
    print("=" * 80)


def test_interface(func_name, func_call, description, return_type='dataframe', max_retries=1):
    """
    测试单个接口
    
    Args:
        func_name: 接口名称
        func_call: 接口调用函数
        description: 接口描述
        return_type: 返回类型 ('dataframe', 'list', 'tuple', 'any')
        max_retries: 最大重试次数
    """
    print_separator(f"测试接口: {func_name}")
    print(f"描述: {description}")
    print(f"开始时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    
    last_error = None
    success = False
    
    try:
        for attempt in range(max_retries):
            try:
                if attempt > 0:
                    print(f"第 {attempt + 1} 次重试...")
                    time.sleep(2)  # 重试前等待2秒
                
                result = func_call()
            
                # 根据返回类型判断是否成功
                if return_type == 'list':
                    if result is not None and isinstance(result, list) and len(result) > 0:
                        print("✓ 成功获取数据")
                        print("数据类型: list")
                        print(f"数据长度: {len(result)}")
                        print(f"数据内容: {result}")
                        success = True
                        break
                    else:
                        print("✗ 接口返回空数据")
                        break
                elif return_type == 'tuple':
                    if result is not None and isinstance(result, tuple):
                        print("✓ 成功获取数据")
                        print("数据类型: tuple")
                        print(f"数据内容: {result}")
                        success = True
                        break
                    else:
                        print("✗ 接口返回空数据")
                        break
                elif return_type == 'dict':
                    if result is not None and isinstance(result, dict):
                        print("✓ 成功获取数据")
                        print("数据类型: dict")
                        print(f"数据内容: {result}")
                        success = True
                        break
                    else:
                        print("✗ 接口返回空数据")
                        break
                else:  # dataframe or any
                    if result is not None and hasattr(result, 'empty') and not result.empty:
                        print("✓ 成功获取数据")
                        print(f"数据形状: {result.shape}")
                        print(f"列名: {list(result.columns)}")
                        print("\n前5行数据:")
                        print(result.head())
                        success = True
                        break
                    else:
                        print("✗ 接口返回空数据")
                        break
                    
            except Exception as e:
                last_error = e
                if attempt < max_retries - 1:
                    continue
                else:
                    # 所有重试均失败
                    print("✗ 接口调用失败")
                    error_msg = str(last_error)
                    if "Connection" in error_msg or "Remote" in error_msg:
                        print("错误类型: 网络连接问题")
                    elif "result" in error_msg:
                        print("错误类型: 数据解析问题")
                    else:
                        print("错误类型: 其他错误")
                    print(f"错误信息: {error_msg[:200]}")
    finally:
        print(f"结束时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    
    return success


def main():
    """主测试函数"""
    print_separator("开始测试akshare期权接口")
    print(f"测试开始时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    
    results = {}
    
    # 1. 合约到期月份列表
    results['option_sse_list_sina'] = test_interface(
        "option_sse_list_sina",
        lambda: ak.option_sse_list_sina(symbol="50ETF"),
        "获取期权-上交所-50ETF-合约到期月份列表",
        return_type='list'
    )
    time.sleep(1)
    
    # 获取一个到期月份用于后续测试
    try:
        month_list = ak.option_sse_list_sina(symbol="50ETF")
        test_month = month_list[0] if isinstance(month_list, list) and len(month_list) > 0 else "202412"
    except Exception:
        test_month = "202412"
    
    # 2. 合约剩余到期时间
    results['option_sse_expire_day_sina'] = test_interface(
        "option_sse_expire_day_sina",
        lambda: ak.option_sse_expire_day_sina(symbol="50ETF", trade_date=test_month),
        f"获取指定到期月份({test_month})的剩余到期时间",
        return_type='tuple'
    )
    time.sleep(1)
    
    # 3. 所有合约的代码
    results['option_sse_codes_sina'] = test_interface(
        "option_sse_codes_sina",
        lambda: ak.option_sse_codes_sina(symbol="50ETF", trade_date=test_month),
        f"获取看涨看跌合约的代码(到期月份: {test_month})"
    )
    time.sleep(1)
    
    # 获取一个合约代码用于后续测试
    try:
        codes_df = ak.option_sse_codes_sina(symbol="50ETF", trade_date=test_month)
        if hasattr(codes_df, 'empty') and not codes_df.empty:
            # 从 DataFrame 中获取第一个合约代码
            test_code = str(codes_df.iloc[0, 1])  # 第二列是期权代码
        else:
            test_code = "10004697"
    except Exception:
        test_code = "10004697"
    
    # 4. 实时数据
    results['option_sse_spot_price_sina'] = test_interface(
        "option_sse_spot_price_sina",
        lambda: ak.option_sse_spot_price_sina(symbol="50ETF"),
        "获取期权实时数据"
    )
    time.sleep(1)
    
    # 5. 期权标的物的实时数据
    results['option_sse_underlying_spot_price_sina'] = test_interface(
        "option_sse_underlying_spot_price_sina",
        lambda: ak.option_sse_underlying_spot_price_sina(symbol="50ETF"),
        "获取期权标的物的实时数据"
    )
    time.sleep(1)
    
    # 6. 期权龙虎榜-金融期权
    results['option_lhb_em'] = test_interface(
        "option_lhb_em",
        lambda: ak.option_lhb_em(
            symbol="510050",
            indicator="期权交易情况-认购交易量",
            trade_date="20241028"
        ),
        "东方财富网-期权龙虎榜单-金融期权"
    )
    time.sleep(1)
    
    # 7. 期权价值分析-金融期权
    results['option_value_analysis_em'] = test_interface(
        "option_value_analysis_em",
        lambda: ak.option_value_analysis_em(),
        "东方财富网-期权价值分析",
        max_retries=2
    )
    time.sleep(1)
    
    # 8. 期权风险分析-金融期权
    results['option_risk_analysis_em'] = test_interface(
        "option_risk_analysis_em",
        lambda: ak.option_risk_analysis_em(),
        "东方财富网-期权风险分析",
        max_retries=2
    )
    time.sleep(1)
    
    # 9. 期权折溢价-金融期权
    results['option_premium_analysis_em'] = test_interface(
        "option_premium_analysis_em",
        lambda: ak.option_premium_analysis_em(),
        "东方财富网-期权折溢价",
        max_retries=2
    )
    time.sleep(1)
    
    # 10. 期权希腊字母信息表
    results['option_sse_greeks_sina'] = test_interface(
        "option_sse_greeks_sina",
        lambda: ak.option_sse_greeks_sina(symbol="50ETF"),
        "新浪财经-期权希腊字母信息表"
    )
    time.sleep(1)
    
    # 11. 期权行情分钟数据
    results['option_sse_minute_sina'] = test_interface(
        "option_sse_minute_sina",
        lambda: ak.option_sse_minute_sina(symbol=test_code),
        f"期权行情分钟数据(合约代码: {test_code})"
    )
    time.sleep(1)
    
    # 12. 期权行情日数据
    results['option_sse_daily_sina'] = test_interface(
        "option_sse_daily_sina",
        lambda: ak.option_sse_daily_sina(symbol=test_code),
        f"期权行情日数据(合约代码: {test_code})"
    )
    time.sleep(1)
    
    # 13. 期权行情分时数据-新浪
    results['option_finance_minute_sina'] = test_interface(
        "option_finance_minute_sina",
        lambda: ak.option_finance_minute_sina(symbol=test_code),
        f"新浪财经-股票期权分时行情数据(合约代码: {test_code})"
    )
    
    # 打印测试总结
    print_separator("测试总结")
    print(f"测试结束时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"\n总共测试接口数: {len(results)}")
    
    success_count = sum(1 for v in results.values() if v)
    fail_count = len(results) - success_count
    
    print(f"成功: {success_count} 个")
    print(f"失败: {fail_count} 个")
    print(f"成功率: {success_count/len(results)*100:.2f}%")
    
    print("\n详细结果:")
    for i, (interface, success) in enumerate(results.items(), 1):
        status = "✓ 成功" if success else "✗ 失败"
        print(f"{i:2d}. {interface:40s} {status}")
    
    print("\n注意事项:")
    if fail_count > 0:
        print("- 部分接口失败可能是由于网络问题或数据源不可用")
        print("- 建议稍后重试或检查网络连接")
    print("- 成功的接口均可正常获取数据")
    
    print("\n" + "=" * 80)


if __name__ == "__main__":
    main()
